package com.five.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.five.api.NovelCategoryServiceApi;
import com.five.api.NovelServiceApi;
import com.five.api.UserServiceAPI;
import com.five.exception.BusinessException;
import com.five.jwt.JwtUtils;
import com.five.jwt.Payload;
import com.five.jwt.RsaUtils;
import com.five.mapper.ReaderMapper;
import com.five.pojo.Comment;
import com.five.pojo.LoginInfo;
import com.five.pojo.Novel;
import com.five.pojo.NovelCategory;
import com.five.pojo.Reader;
import com.five.result.Result;
import com.five.service.ReaderService;
import com.five.vo.NovelRankVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.net.URLDecoder;
import java.security.PublicKey;
import java.util.*;

@Service
public class ReaderServiceImpl implements ReaderService {
    @Autowired
    private ReaderMapper readerMapper;

    @Autowired
    private NovelCategoryServiceApi novelCategoryServiceApi;

    @Autowired
    private NovelServiceApi novelServiceAPI;

    /**
     * 根据手机号查询作者信息
     * @param phone
     * @return
     */
    @Override
    public Reader queryByPhone(String phone) {
        if (phone == null || phone.trim().length() == 0){
            throw new BusinessException("手机号不能为空");
        }
        return readerMapper.queryByPhone(phone);
    }

    /**
     * 根据邮箱查询作者信息
     * @param email
     * @return
     */
    @Override
    public Reader queryByEmail(String email) {
        if (email == null || email.trim().length() == 0){
            throw new BusinessException("邮箱不能为空");
        }
        return readerMapper.queryByEmail(email);
    }

    /**
     * 根据登录信息ID查询作者信息
     * @param loginInfoId
     * @return
     */
    @Override
    public Reader queryByLoginInfoId(Long loginInfoId) {
        if (loginInfoId == null){
            throw new BusinessException("登录信息ID不能为空");
        }
        return readerMapper.queryByLoginInfoId(loginInfoId);
    }

    /**
     * 新增作者信息
     * @param reader
     */
    @Override
    public void insertReader(Reader reader) {
        if (reader == null){
            throw new BusinessException("作者信息不能为空");
        }
        readerMapper.insert(reader);
    }

    /**
     * 更新作者信息
     * @param reader
     */
    @Override
    public void updateReader(Reader reader) {
        if (reader == null){
            throw new BusinessException("作者信息不能为空");
        }
        readerMapper.update(reader);
    }

    /**
     * 根据账号查询读者信息
     * @param account
     */
    @Override
    public Reader queryByAccount(String account) {
        if (account == null || account.trim().length() == 0){
            throw new BusinessException("账号不能为空");
        }
        return readerMapper.queryByAccount(account);
    }
    /**
     * 修改读者密码
     * @param newPassword
     */

    @Override
    public void updatePassword(String newPassword,Long  id) {
        if (newPassword == null || newPassword.trim().length() == 0){
            throw new BusinessException("密码不能为空");
        }
        String salt = UUID.randomUUID().toString();
        String md5Password = DigestUtils.md5DigestAsHex((salt + newPassword).getBytes());
        readerMapper.updatePassword(md5Password,id);
    }

    /**
  *修改读者信息
     */
    @Override
    public void update(Reader reader) {
        readerMapper.update(reader);
    }

    /**
     * 注销账号
     */
    @Override
    public void deleteByLoginInfoId(Long id) {
        readerMapper.deleteByLoginInfoId(id);
        //删除reader账号同时要删除登录表中的账号信息
        readerMapper.deleteLogininfoById(id);

    }

    /**
     * 根据小说id查询读者对该书的评论及回复
     * @param novelId
     * @return
     */
    @Override
    public List<Comment> getCommentByNovelId(Long novelId) {

        return readerMapper.getCommentByNovelId(novelId);
    }

    /**
     * 更新评论的回复数量
     * @param commentId
     */
    @Override
    public void updateReplyCount(Long commentId) {
        readerMapper.updateReplyCount(commentId);
    }

    @Override
    public Integer getReaderTypeById(String token) {
        LoginInfo loginInfo = tokenToLoginInfo(token);
        Long loginInfoId = loginInfo.getId();
        Integer type = readerMapper.selectGenderByLoginInfoId(loginInfoId);
        return type;
    }

    @Override
    public List<NovelCategory> getNovelTreeByType(Long type) {
        Result tree = novelCategoryServiceApi.tree(type);
        return List.class.cast(tree.getData());
    }

    @Override
    public List<NovelRankVo> rankTop10Collect() {
        Result<List<NovelRankVo>> listResult = novelServiceAPI.top10Collect();
        List<NovelRankVo> data = listResult.getData();
        if (data != null && data.size() > 0) {
            return data;
        }
        return new ArrayList<>();
    }

    @Override
    public List<NovelRankVo> listNovelByCategory(Long categoryId) {
        if (categoryId == null || categoryId <= 0) {
            throw new BusinessException("分类 ID 非法");
        }
        return readerMapper.selectByCategoryId(categoryId);
    }



    /*
     * 根据token获取登录人信息
     * */
    public LoginInfo tokenToLoginInfo(String token) {
        PublicKey publicKey;
        LoginInfo logininfo;
        try {
            publicKey = RsaUtils.getPublicKey(URLDecoder.decode(
                    JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile(), "UTF-8"));
            Payload<Map> payload = JwtUtils.getInfoFromToken(token, publicKey, Map.class);
            // 4. 获取"loginInfo"对应的JSON对象，并转换为LoginInfo
            Object loginInfoObj = payload.getUserInfo().get("loginInfo");
            // 关键：使用FastJSON将JSON对象反序列化为LoginInfo（核心解决类型转换问题）
            logininfo = JSON.toJavaObject((JSONObject) loginInfoObj, LoginInfo.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return logininfo;
    }

}